#include "humi.h"
 
char tempStr[20] = {0};
char humiStr[20] = {0};
double temp_value = 0;
double humi_value = 0;

int pinNumber = 26;  //use gpio1 to read data
uint32 databuf;

int humi_init(void)
{
    pinMode(pinNumber, OUTPUT); // set mode to output
    digitalWrite(pinNumber, 1); // output a high level
}
 
uint8 humi_readData(void)
{
    uint8 crc; 
    uint8 i;
 
    pinMode(pinNumber,OUTPUT); // set mode to output
    digitalWrite(pinNumber, 1); // output a low level
    delayMicroseconds(4);
    digitalWrite(pinNumber, 0); // output a high level 
    delay(25);
    digitalWrite(pinNumber, 1); // output a low level
    delayMicroseconds(60); 
    pinMode(pinNumber, INPUT); // set mode to input
    pullUpDnControl(pinNumber,PUD_UP);
 
    if(digitalRead(pinNumber)==0) //SENSOR ANS
    {
        while(!digitalRead(pinNumber)); //wait to high
        delayMicroseconds(80);
        for(i=0;i<32;i++)
        {
          while(digitalRead(pinNumber)); //data clock start
          while(!digitalRead(pinNumber)); //data start
          delayMicroseconds(HIGH_TIME);
          databuf*=2;
          if(digitalRead(pinNumber)==1) //1
          {
            databuf++;
          }
        }
 
        for(i=0;i<8;i++)
        {
          while(digitalRead(pinNumber)); //data clock start
          while(!digitalRead(pinNumber)); //data start
          delayMicroseconds(HIGH_TIME);
          crc*=2;  
          if(digitalRead(pinNumber)==1) //1
          {
            crc++;
          }
        }
      return 1;
    }
    else
    {
      return 0;
    }
}
 
void humi_getValue(void)
{
		pinMode(pinNumber,OUTPUT); // set mode to output
		digitalWrite(pinNumber, 1); // output a high level 
        delay(200);

        if(humi_readData())
		{
            humi_value = (float)((databuf>>24)&0xff) + (float)(((databuf>>16)&0xff)*0.1);
            temp_value = (float)((databuf>>8)&0xff) + (float)((databuf&0xff)*0.1);
            sprintf(humiStr, "%.1f",humi_value);
            sprintf(tempStr, "%.1f",temp_value);
            databuf=0;
		}
		else
		{
			printf("Error!\n");
			databuf=0;
		}
}
